package com.chookss.home.workbench;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.ContactEntity;
import com.chookss.home.logContacts.ContactsLogChoiceActivity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.Utils;
import com.chookss.view.CircleImageView;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class WorkChoiceActivity extends BaseAct {
    @BindView(R.id.tvCompany)
    TextView tvCompany;
    @BindView(R.id.common_title_txt)
    TextView common_title_txt;
    @BindView(R.id.tvAudit)
    TextView tvAudit;
    @BindView(R.id.tvAudited)
    TextView tvAudited;
    @BindView(R.id.llChoiceType)
    LinearLayout llChoiceType;
    @BindView(R.id.llAudited)
    LinearLayout llAudited;
    @BindView(R.id.llAuditedType)
    LinearLayout llAuditedType;
    @BindView(R.id.tvStartTime)
    TextView tvStartTime;
    @BindView(R.id.tvEndTime)
    TextView tvEndTime;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.spaceViewAudited)
    View spaceViewAudited;
    private String companyName = "";
    private String startTime = "", endTime = "";
    private MyContactEntityAdapter adapter;
    private int position = 0;//0待审核进来的1已审核
    private String pass = "";//1通过0未通过
    private List<ContactEntity> selectList = new ArrayList<>();
    private List<ContactEntity> cacheList = new ArrayList<>(); //缓存
    private static int SOURSE = 5;//选员工所用标识

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_work_choice);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        common_title_txt.setText("筛选");
        startTime = getIntent().getStringExtra("startTime");
        endTime = getIntent().getStringExtra("endTime");
        position = getIntent().getIntExtra("position", 0);
        pass = getIntent().getStringExtra("pass");
        selectList.clear();
        cacheList.clear();
        cacheList = (List<ContactEntity>) getIntent().getSerializableExtra("selectList");
        selectList.addAll(cacheList);
        for (int i = 0; i < selectList.size(); i++) {
            if (selectList.get(i).isHalfSelect()) {
                selectList.remove(i);
                if (i < selectList.size()) {
                    i--;
                }
            }
        }
        ContactEntity contactEntity = new ContactEntity();
        contactEntity.setEmployeeCode("0");
        selectList.add(contactEntity);
        GridLayoutManager gridLayoutManager1 = new GridLayoutManager(this, 6);
        recyclerView.setLayoutManager(gridLayoutManager1);
        adapter = new MyContactEntityAdapter(R.layout.item_log_choice, this, selectList);
        recyclerView.setAdapter(adapter);
        initView(position);
        if (!Utils.isNull(startTime)) {
            tvStartTime.setText(startTime);
        }
        if (!Utils.isNull(endTime)) {
            tvEndTime.setText(endTime);
        }
        companyName = new ShareUtils().getString(this, StaticClass.COMPANYNAME, "");
        if (Utils.isNull(companyName)) {
            companyName = getResources().getString(R.string.app_name);
        }
        tvCompany.setText(companyName);
    }

    private void initView(int position) {
        if (llChoiceType == null) {
            return;
        }
        for (int i = 0; i < 2; i++) {
            if (position == i) {
                llChoiceType.getChildAt(i).setSelected(true);
            } else {
                llChoiceType.getChildAt(i).setSelected(false);
            }
        }
        if (position == 1) {
            llAudited.setVisibility(View.VISIBLE);
            spaceViewAudited.setVisibility(View.VISIBLE);
            if ("0".equals(pass)) {
                initAuditedView(1);
            } else if ("1".equals(pass)) {
                initAuditedView(0);
            } else {
                initAuditedView(-1);
            }
        } else {
            llAudited.setVisibility(View.GONE);
            spaceViewAudited.setVisibility(View.GONE);
        }
    }

    private void initAuditedView(int position) {
        if (llAuditedType == null) {
            return;
        }
        for (int i = 0; i < 2; i++) {
            if (position == i) {
                llAuditedType.getChildAt(i).setSelected(true);
            } else {
                llAuditedType.getChildAt(i).setSelected(false);
            }
        }
    }

    @OnClick({R.id.common_title_back, R.id.tvAudit, R.id.tvAudited, R.id.tvPass, R.id.tvNoPass, R.id.llStartTime, R.id.llEndTime, R.id.tvCancel, R.id.tvSure})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.tvAudit:
//                initView(0);
                break;
            case R.id.tvAudited:
//                initView(1);
                break;
            case R.id.tvPass:
                pass = "1";
                initAuditedView(0);
                break;
            case R.id.tvNoPass:
                pass = "0";
                initAuditedView(1);
                break;
            case R.id.llStartTime:
                if (tvStartTime == null) {
                    return;
                }
                showDatePickDialog(tvStartTime.getText().toString(), 0);
                break;
            case R.id.llEndTime:
                if (tvEndTime == null) {
                    return;
                }
                showDatePickDialog(tvEndTime.getText().toString(), 1);
                break;
            case R.id.tvCancel:
                if (tvStartTime == null) {
                    return;
                }
                initAuditedView(-1);
                startTime = "";
                endTime = "";
                pass = "";
                tvStartTime.setText("");
                tvEndTime.setText("");
                selectList.clear();
                cacheList.clear();
                ContactEntity contactEntity = new ContactEntity();
                contactEntity.setEmployeeCode("0");
                selectList.add(contactEntity);
                adapter.notifyDataSetChanged();
                break;
            case R.id.tvSure:
                if (tvStartTime == null) {
                    return;
                }
                if (!Utils.isNull(tvStartTime.getText().toString())) {
                    if (Utils.isNull(tvEndTime.getText().toString())) {
                        MyToast.show("请选择结束时间");
                        return;
                    }
                    if (Utils.getTimeCompareSize(tvStartTime.getText().toString(), tvEndTime.getText().toString()) == 1) {
                        MyToast.show("结束时间不能小于起始时间");
                        return;
                    }
                }
                if (!Utils.isNull(tvEndTime.getText().toString())) {
                    if (Utils.isNull(tvStartTime.getText().toString())) {
                        MyToast.show("请选择起始时间");
                        return;
                    }
                    if (Utils.getTimeCompareSize(tvStartTime.getText().toString(), tvEndTime.getText().toString()) == 1) {
                        MyToast.show("结束时间不能小于起始时间");
                        return;
                    }
                }
                Intent intent = new Intent();
                intent.putExtra("startTime", tvStartTime.getText().toString());
                intent.putExtra("endTime", tvEndTime.getText().toString());
                intent.putExtra("pass", pass);
                intent.putExtra("data", (Serializable) cacheList);
                setResult(1, intent);
                finish();
                break;
        }
    }

    private void showDatePickDialog(String curDate, int type) {
        //获取日历的一个实例，里面包含了当前的年月日
        Calendar calendar = Calendar.getInstance();
        int year = 0, month = 0, day = 0;
        try {
            if (Utils.isNull(curDate)) {
                year = calendar.get(Calendar.YEAR);
                month = calendar.get(Calendar.MONTH);
                day = calendar.get(Calendar.DAY_OF_MONTH);
            } else {
                year = Integer.parseInt(curDate.substring(0, curDate.indexOf("-")));
                month = Integer.parseInt(curDate.substring(curDate.indexOf("-") + 1, curDate.lastIndexOf("-"))) - 1;
                day = Integer.parseInt(curDate.substring(curDate.lastIndexOf("-") + 1, curDate.length()));
            }

        } catch (Exception e) {
            e.printStackTrace();
            year = calendar.get(Calendar.YEAR);
            month = calendar.get(Calendar.MONTH);
            day = calendar.get(Calendar.DAY_OF_MONTH);
        }
        if (tvStartTime == null) {
            return;
        }
        //构建一个日期对话框，该对话框已经集成了日期选择器
        //DatePickerDialog的第二个构造参数指定了日期监听器
        DatePickerDialog dialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                String choiceMonth = "0", choiceDay = " 0";
                if (month + 1 > 9) {
                    choiceMonth = (month + 1) + "";
                } else {
                    choiceMonth = "0" + (month + 1);
                }
                if (dayOfMonth > 9) {
                    choiceDay = dayOfMonth + "";
                } else {
                    choiceDay = "0" + dayOfMonth;
                }
                if (type == 0) {
                    tvStartTime.setText(year + "-" + choiceMonth + "-" + choiceDay);
                } else {
                    tvEndTime.setText(year + "-" + choiceMonth + "-" + choiceDay);
                    if (!Utils.isNull(tvStartTime.getText().toString())) {
                        if (Utils.getTimeCompareSize(tvStartTime.getText().toString(), tvEndTime.getText().toString()) == 1) {
                            MyToast.show("结束时间不能小于起始时间");
                            tvEndTime.setText("");
                            return;
                        }
                    }
                }

            }
        },
                year,
                month,
                day);
        //把日期对话框显示在界面上
        dialog.show();
    }

    class MyContactEntityAdapter extends BaseQuickAdapter<ContactEntity, BaseViewHolderEx> {
        private Context context;

        public MyContactEntityAdapter(int layoutResId, Context context,
                                      @io.reactivex.annotations.Nullable List<ContactEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, ContactEntity item) {
            CircleImageView ivHead = helper.getView(R.id.ivHead);
            ImageView ivAdd = helper.getView(R.id.ivAdd);
            TextView tvName = helper.getView(R.id.tvName);
            if (helper.getItemPosition() == selectList.size() - 1) {
                ivAdd.setVisibility(View.VISIBLE);
                ivHead.setVisibility(View.GONE);
                tvName.setVisibility(View.GONE);
            } else {
                ivAdd.setVisibility(View.GONE);
                if ("0".equals(item.getType())) {
//                    部门
                    ivHead.setVisibility(View.GONE);
                    tvName.setVisibility(View.VISIBLE);
                    tvName.setText(item.getEmployeeName());
                } else {
                    //员工
                    ivHead.setVisibility(View.VISIBLE);
                    tvName.setVisibility(View.GONE);
                    GlideUtils.loadAvatar(WorkChoiceActivity.this, item.getHeadPhotoThumbUrl(),
                            ivHead);
                }
            }
            ivAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(WorkChoiceActivity.this, ContactsLogChoiceActivity.class);
                    MyApp.contactEntityLogList.clear();
                    MyApp.contactEntityLogList.addAll(cacheList);
                    intent.putExtra("source", SOURSE + "");
                    startActivity(intent);
                }
            });
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();

        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if (msg.equals("ChoiceContacts_Ok_" + SOURSE)) {
                if (recyclerView == null) {
                    return;
                }
                selectList.clear();
                cacheList.clear();
                selectList.addAll(MyApp.contactEntityLogList);
                cacheList.addAll(MyApp.contactEntityLogList);
                for (int i = 0; i < selectList.size(); i++) {
                    if (selectList.get(i).isHalfSelect()) {
                        selectList.remove(i);
                        if (i < selectList.size()) {
                            i--;
                        }
                    }
                }
                ContactEntity contactEntity = new ContactEntity();
                contactEntity.setEmployeeCode("0");
                selectList.add(contactEntity);
                adapter.notifyDataSetChanged();
            }
        }
    }
}
